﻿package  control 
{
	import com.snzflash.events.MediaEvent;
	import com.snzflash.events.NavigationEvent;
	import com.snzflash.media.VideoPlayer;
	import com.snzflash.utils.Formatter;
	import flash.accessibility.AccessibilityProperties;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageDisplayState;
	import flash.events.Event;
	import flash.events.FullScreenEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.media.Video;
	import gs.TweenLite;
	/**
	 * Контрол для видео, базовый класс
	 * @author firsoff maxim, tel: +79222345364, skype: maxim.firsoff
	 */
	public class VideoViewBase extends Sprite
	{
		
		// PROPERTIES
	
		// public
		public var videoBackground:Sprite;
		public var startButton:Sprite;
		public var controlbar:ControlBar;
		// папка для видео
		public var videoFolder:Sprite
		// само видео
		private var _video:VideoPlayer;
		// состояние
		private var _state:String;
		// private
		private var _isFullscreen:Boolean;
		// == STATIC==
		
		
		// CONSTRUCTOR
		public function VideoViewBase() 
		{
			super();
			
			
			
			init();
		};
		
		
		
		// METHODS
	
		// public
		
		// private
		
		private function init():void
		{
			// создаем видео
			videoFolder = new Sprite();
			addChildAt(videoFolder, getChildIndex(videoBackground) + 1);
			
			// события стартовой кнопки
			startButton.buttonMode = startButton.useHandCursor = true;
			startButton.addEventListener(MouseEvent.CLICK, onStartButtonClick);
			
			// события конрола
			controlbar.addEventListener(NavigationEvent.VOLUME, onVolumeChange);
			controlbar.addEventListener(NavigationEvent.SEEK, onSeek);
			controlbar.addEventListener(NavigationEvent.PLAY, onPlay);
			controlbar.addEventListener(NavigationEvent.PAUSE, onPause);
			controlbar.addEventListener(NavigationEvent.FULLSCREEN, toggleFullScreen);
			controlbar.addEventListener(NavigationEvent.NORMAL_SCREEN, toggleFullScreen);
			
			
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			//trace(Formatter.secondsToHM(80).s);
		};
		
		private function onAddedToStage(event:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			stage.addEventListener(FullScreenEvent.FULL_SCREEN, onStageFullScreenChanged);
		};
		
		

		
		private function getTimeFormattedString(obj:Object):String
		{
			var result:String = '';
			var m:String = obj.m;
			m = m.length == 1 ? '0' + m : m;
			result = m  + ':'
			
			var s:String = obj.s;
			s = s.length == 1 ? '0' + s : s;
			result +=  s;
			return result
		};
		
		
		private function hideStartButton():void
		{
			startButton.removeEventListener(MouseEvent.CLICK, onStartButtonClick);
			TweenLite.to(startButton, 0.4, { alpha : 0 } );
		};
		
		/**
		 * Сброс
		 */
		private function reset():void
		{
			controlbar.reset();
		};
		
		// getters/setters
		public function get isFullscreen():Boolean { return _isFullscreen; };
		
		public function set isFullscreen(value:Boolean):void 
		{
			_isFullscreen = value;
		};
		
		public function set volume(value:Number):void 
		{
			controlbar.volume = value;
		};
		
		public function get volume() :Number{ return controlbar.volume; }
		
		public function get video():VideoPlayer { return _video; };
				
		public function set video(value:VideoPlayer):void 
		{
			_video = value;
			videoFolder.addChild(_video);
			
			// подключение всех событий
			_video.addEventListener(MediaEvent.LOADING_PROGRESS, onVideoLoadingProgress);
			_video.addEventListener(MediaEvent.PLAYING_PROGRESS, onVideoPlayingProgress);
			_video.addEventListener(MediaEvent.VIDEO_INIT, onVideoInit);
		};
		
		public function get videoWidth():Number { return videoBackground.width; }
		public function get videoHeight():Number { return videoBackground.height; }
		
		public function get state():String { return _state; };
		
		public function set state(value:String):void 
		{
			_state = value;
			controlbar.state = value;
			switch (value) 
			{
				case VideoPlayer.PAUSED:
					
				break;
				
				case VideoPlayer.PLAYING:
					// при переходе на проигрывание - убираем кнопку
					hideStartButton();
				break;
			}
		};
		// == STATIC==
		
		
		// HANDLERS
		/**
		 * При клике на кнопку
		 * @param	event
		 */
		private function onStartButtonClick(event:MouseEvent = null):void 
		{
			state = VideoPlayer.PLAYING;
			_video.play();
		};
		
		private function onVideoLoadingProgress(event:MediaEvent):void 
		{
			//if (event.data is NaN) return;
			controlbar.trackBar.loadProgress = Number(event.data);
			//trace((event.data));
		};
		
		private function onVideoPlayingProgress(event:MediaEvent):void 
		{
			//trace(event.data);
			controlbar.trackBar.playProgress = Number(event.data);
			var seconds:Number = Number(event.data) * _video.duration;
			//var formatter_object:Object = Formatter.secondsToHM(seconds);
			
			controlbar.elapsedText.text = getTimeFormattedString( Formatter.secondsToHM(seconds) );
			//trace(formatter_object.m);
		};
		
		private function onVolumeChange(event:NavigationEvent):void 
		{
			_video.volume = Number(event.data);
		};
		
		private function onPause(event:NavigationEvent):void 
		{
			_video.pause();
		};
		
		private function onPlay(event:NavigationEvent):void 
		{
			_video.resume();
		};
		
		/**
		 * При инициализации видео
		 * @param	event
		 */
		private function onVideoInit(event:MediaEvent):void 
		{
			// установка размера
			var w:Number = event.data.width;
			var h:Number = event.data.height;
			var ratio:Number = Math.min( videoBackground.width / event.data.width , videoBackground.height / event.data.height);
			_video.width = w * ratio;
			_video.height = h * ratio;
			// выравнивание по центру
			_video.x = Math.round((videoBackground.width - _video.width) / 2);
			_video.y = Math.round((videoBackground.height - _video.height) / 2);
			// устанавливаем продолжительность
			controlbar.totalText.text = getTimeFormattedString(Formatter.secondsToHM(_video.duration));
		};
		
		private function onSeek(event:NavigationEvent):void 
		{
			//trace(event.data);
			_video.seekByPercent(Number(event.data));
		};
		
		/**
		 * При изменении на Esc клавишу
		 * @param	event
		 */
		private function onStageFullScreenChanged(event:FullScreenEvent):void 
		{
			 switch(stage.displayState) 
			{
                case StageDisplayState.NORMAL:
                   controlbar.fullscreen = false;
                break;
				
                case StageDisplayState.FULL_SCREEN:
					controlbar.fullscreen = true;
				break;
				
                default:
                   controlbar.fullscreen = false;  
                break;
            };
		};
		
		
	/**
	 * При изменении через кнопки
	 * @param	event
	 */
		private function toggleFullScreen(event:NavigationEvent):void 
		{
            switch(stage.displayState) 
			{
                case StageDisplayState.NORMAL:
					// задаем прямоугольник для фул скрина
					var viewRect:Rectangle = new Rectangle(0, 0, width, height);
					stage.fullScreenSourceRect = viewRect;
					
					stage.displayState = StageDisplayState.FULL_SCREEN;
                break;
				
                case StageDisplayState.FULL_SCREEN:
					stage.displayState = StageDisplayState.NORMAL;
				break;
				
                default:
                    stage.displayState = "normal";    
                 break;
            };
        } ;   
	};

};